import requests
import semver
from typing import Optional

class UpdateChecker:
    """
    Gitee版本更新检测器
    
    功能：
    - 通过Gitee API获取最新发行版
    - 语义化版本比对
    - 增量更新包下载
    """
    
    def __init__(self, owner: str = 'YeMiao_cats', repo: str = 'SmartLedger'):
        self.api_url = f'https://gitee.com/api/v5/repos/{owner}/{repo}/releases/latest'
        
    def check_update(self, current_version: str) -> Optional[dict]:
        """检查可用更新"""
        try:
            response = requests.get(self.api_url, timeout=10)
            if response.status_code == 200:
                latest = response.json()
                if semver.compare(latest['tag_name'], current_version) > 0:
                    return {
                        'version': latest['tag_name'],
                        'notes': latest['body'],
                        'zip_url': latest['zipball_url'],
                        'published_at': latest['created_at']
                    }
        except Exception as e:
            print(f"更新检查失败: {str(e)}")
        return None

    def download_update(self, url: str, save_path: str = 'update.zip') -> bool:
        """下载更新包"""
        try:
            with requests.get(url, stream=True) as r:
                r.raise_for_status()
                with open(save_path, 'wb') as f:
                    for chunk in r.iter_content(chunk_size=8192):
                        f.write(chunk)
            return True
        except Exception as e:
            print(f"下载失败: {str(e)}")
            return False